package br.com.saeng2D.util;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

public class TextFieldNumero extends JTextField {
	private static final long serialVersionUID = 1L;
	private int maximo;
	
	public TextFieldNumero(int maximo) {
		this.maximo = maximo;
		registrarEvento();
	}

	private void registrarEvento() {
		addKeyListener(new KeyListener() {
			public void keyTyped(KeyEvent e) {
				processar(e);
			}
			public void keyReleased(KeyEvent e) {
				processar(e);
			}
			public void keyPressed(KeyEvent e) {
				processar(e);
			}
		});
	}
	
	private void processar(KeyEvent e) {
		if(getText().length() >= maximo) {
			e.consume();
		}
		
		if(!((e.getKeyChar() >= '0' && e.getKeyChar() <= '9') || (e.getKeyChar() == '\b'))) {
			e.consume();
		}
	}
}